package com.wwl.springcloud.controller;

import com.wwl.springcloud.dto.CommonResult;
import com.wwl.springcloud.entity.Order;
import com.wwl.springcloud.repository.OrderRepository;
import com.wwl.springcloud.service.StorageService;
import io.seata.spring.annotation.GlobalTransactional;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Optional;

/**
 * @author wwl
 * @version 1.0
 * @date 2021/8/23 11:21
 * @description:
 */
@Slf4j
@RestController
@Api(value = "/order", description = "订单", tags = {"order"})
public class OrderController {

    @Autowired
    private OrderRepository orderRepository;

    @Resource
    private StorageService storageService;


    private CommonResult commonResult = CommonResult.getInstance();

    /**
     * 新增或编辑
     */
    @ApiOperation("新增订单")
    @PostMapping("/create")
    @GlobalTransactional
    public CommonResult save(@RequestBody Order order) {
        log.info("------>开始新建订单");
        order.setStatus(1);
        order.setUserId(2L);
        Order order1 = orderRepository.save(order);

        log.info("----->订单微服务开始调用库存，做扣减Count");
        storageService.decrease(order.getProductId().intValue(),order.getCount());
        log.info("----->订单微服务开始调用库存，做扣减end");


        return commonResult.success(order1);
    }

    /**
     * 删除
     */
    @ApiOperation("删除订单")
    @PostMapping("/delete")
    public Object delete(int id) {
        Optional<Order> tOrder = orderRepository.findById(id);
        if (tOrder.isPresent()) {
            orderRepository.deleteById(id);
            return commonResult.success("删除成功");
        } else {
            return commonResult.error("没有找到该对象");
        }
    }

    /**
     * 查询
     */
    @ApiOperation("查询订单")
    @PostMapping("/find")
    public Object find(int id) {
        Optional<Order> tOrder = orderRepository.findById(id);
        if (tOrder.isPresent()) {
            return commonResult.success(tOrder.get());
        } else {
            return commonResult.error("没有找到该对象");
        }
    }


}
